package DBLayer;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnection
{
	
	private final static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
	//private final static String driver = "net.sourceforge.jtds.jdbc.Driver";
	//private final static String driver = "com.mysql.jdbc.Driver";
	
	private final static String dbEngine     = "jdbc:sqlserver://balder.ucn.dk";
	private final static String databaseName = ";databaseName = DM79_4";
	private final static String userName     = ";user = DM79_4";
	private final static String password     = ";password = MaaGodt";
		

/*
	private final static String dbEngine     = "jdbc:sqlserver://192.168.15.112:1433";
	private final static String databaseName = ";databaseName = DM79_4";
	private final static String userName     = ";user = sa";
	private final static String password     = ";password = RaaDataBase";
*/
	//private static DatabaseMetaData dmd;
	private static DBConnection instance = null;
	private static Connection conn;
  private static boolean error;
	
	private static Exception exception;
	
	private DBConnection()
	{
		error = false;
    try
    {
    	Class.forName(driver);
    }
    catch (Exception e)
    {
    	exception = e; 
    	error = true;
    }
    if (!error)
    {//Driver is loaded!
    	String url = dbEngine + databaseName + userName + password;	    	
    	try
    	{
    		conn = DriverManager.getConnection(url);
    	}
    	catch (Exception e)
    	{
    		exception = e;
    		error = true;
    	}
    } // if
	} // DBConnection
	
	public static Exception getException() {return error?exception:null;}
	
	public Connection getConnection() {return error?null:conn;}
	
	public static DBConnection getInstance()
	{
		if (instance == null)
		{
		  instance = new DBConnection();
		}
	  return error?null:instance;
	} //getInstance
	
	// returns TRUE if succeeded
	public static boolean closeDBConnection()
	{
		try
		{
			conn.close();
			instance = null;
		}
		catch (Exception e)
		{
			exception = e;
			error = true;
		}
		return !error;
	}
	
//returns TRUE if succeeded
	public static boolean startTransaction()
	{
		try
		{
			conn.setAutoCommit(false);
		}
		catch (Exception e)
		{
			exception = e;
			error = true;
		}
		return !error;
	}
	
//returns TRUE if succeeded
	public static boolean commitTransaction()
	{
		try
		{
			conn.setAutoCommit(true);
		}
		catch (Exception e)
		{
			exception = e;
			error = true;
		}
		return !error;
	}
	
//returns TRUE if succeeded
	public static boolean rollbackTransaction()
	{
		try
		{
			conn.rollback();
			conn.setAutoCommit(true);
		}
		catch (Exception e)
		{
			exception = e;
			error = true;
		}
		return !error;
	}

}// end DBConnection
